import type { CardListItemProps, CardListProps } from './components/goods-card-list/types.ts'
import type { RadioGroupProps } from './components/radio-group/types.ts'
import type { PageHelperType } from './types.ts'
import { throttle } from 'lodash'
import React, { useState } from 'react'
import GoodsCardList from './components/goods-card-list/goods-card-list-2.tsx'
import RadioGroup from './components/radio-group/radio-group.tsx'
import StreamList from './components/stream-list/stream-list.tsx'

// 随机1-10000之间的数字
function randomNum(option: {
  min?: number
  max?: number
} = {}): number {
  const min = option.min ?? 1
  const max = option.max ?? 10000
  return Math.floor(Math.random() * (max - min)) + min
}

// 随机生成1-200个汉字
function randomChinese(option: {
  min?: number
  max?: number
} = {}): string {
  const min = option.min || 1
  const max = option.max || 200
  const randomLength = Math.floor(Math.random() * (max - min + 1)) + min
  return getRandomChineseChars(randomLength)
}

function getRandomChineseChars(length: number): string {
  const start = 0x4E00
  const end = 0x9FFF
  let result = ''
  for (let i = 0; i < length; i++) {
    const randomCode = Math.floor(Math.random() * (end - start + 1)) + start
    result += String.fromCharCode(randomCode)
  }
  return result
}

const App: React.FC = () => {
  const [cardListDataList, setCardListDataList] = useState<CardListItemProps[]>([])

  const props1: RadioGroupProps = {
    options: [
      { label: '非遗地方特色', value: '1' },
      { label: '精选产品', value: '2' },
    ],
    defaultValue: '1',
    type: 'button',
    isWrap: false,
    onChange: (value: string) => {
      console.log(value)
    },
  }

  const props2: RadioGroupProps = {
    options: [
      { label: '摆件', value: '1' },
      { label: '茶文化', value: '2' },
      { label: '生活', value: '3' },
      { label: '书法', value: '4' },
    ],
    defaultValue: '1',
    type: 'text',
    isWrap: false,
    onChange: (value: string) => {
      console.log(value)
    },
  }
  // 最大的数量
  const total = 13
  const DEFAULT_LIST: CardListItemProps[] = Array.from({ length: total }).map((_, index) => {
    const id = `${index}`
    const hasActivePrice = Math.random() > 0.5
    const price = randomNum({ min: 1, max: 1000000 })
    return {
      key: id,
      imageList: Array.from({ length: randomNum({ min: 1, max: 10 }) }).map((_, index) => {
        return `https://loremflickr.com/400/300/food?id=${id}_${index}`
      }),
      title: randomChinese({ min: 6, max: 20 }),
      desc: randomChinese({ min: 10, max: 100 }),
      price: `${(price / 100).toFixed(2)}`,
      activePrice: hasActivePrice ? `${(randomNum({ min: 1, max: price }) / 100).toFixed(2)}` : undefined,
      sales: randomNum({ min: 100, max: 100000 }),
    } as CardListItemProps
  })

  function loadData(page: number = 1, rows: number = 10): Promise<PageHelperType<CardListItemProps>> {
    return new Promise((resolve) => {
      // 模拟分页，取出上述列表中的值
      const start = (page - 1) * rows
      const end = start + rows
      const array = DEFAULT_LIST.slice(start, end)
      // 计算是否是最后一页
      const isLastPage = end >= total
      setTimeout(() => {
        resolve({
          page,
          rows,
          isLastPage,
          list: array,
          total,
        })
      }, 300)
    })
  }

  const throttleLoadData = throttle(loadData, 150)

  const props3: CardListProps = {
    dataList: cardListDataList,
    onClick: (value) => {
      console.log(value)
    },
  }

  const fetchData = async (page: number, rows: number): Promise<PageHelperType> => {
    return throttleLoadData(page, rows).then((data) => {
      // 更新数据列表
      setCardListDataList(prevData => [...prevData, ...data.list])
      return Promise.resolve(data)
    })
  }

  return (
    <>
      <div className="p2">
        <RadioGroup {...props1} />
        <RadioGroup {...props2} />
        <br />
        <StreamList
          onNextPage={(page, rows) => fetchData(page, rows)}
          onRefreshPage={() => {
            setCardListDataList([])
            return fetchData(1, 10)
          }}
        >
          <GoodsCardList {...props3} />
        </StreamList>
      </div>
    </>
  )
}

export default App
